using System.Collections.Generic;
using Crawler.DomainServices.Processors;
using HtmlAgilityPack;

namespace Crawler.ContentProcessors
{
	class HtmlParserHelper : IHtmlParserHelper
	{
		public string GetInnerTextOfSingleNode(HtmlNode src, string xpath)
		{
			var node = GetInnerNode(src, xpath);
			
			return node!=null?node.InnerText:string.Empty;
		}

		public HtmlNode GetInnerNode(HtmlNode src, string xpath)
		{
			var doc = new HtmlDocument();
			doc.LoadHtml(src.InnerHtml);

			var node = doc.DocumentNode.SelectSingleNode(xpath);
			return node;
		}

		public IEnumerable<HtmlNode> GetInnerNodeCollection(HtmlNode src,string xPath)
		{
			var doc = new HtmlDocument();
			doc.LoadHtml(src.InnerHtml);

			var nodes = doc.DocumentNode.SelectNodes(xPath);
			return nodes;
		}

		public string GetAttributeValueOfSingleNode(HtmlNode src, string xPath, string attributeName)
		{
			return GetInnerNode(src, xPath).Attributes[attributeName].Value;
		}

		public string GetInnerTextOfSingleNodeFromCollection(HtmlNode src, string xPathCollectionFilter, string xPath)
		{
			HtmlNode innerNode = GetInnerNode(src, xPathCollectionFilter);
			return GetInnerTextOfSingleNode(innerNode, xPath);
		}
	}
}